package com.sunstar.club.subject.domain.service.impl;

import com.alibaba.fastjson.JSON;
import com.sunstar.club.subject.common.enums.IsDeletedFlagEnum;
import com.sunstar.club.subject.common.result.PageResult;
import com.sunstar.club.subject.domain.convert.SubjectInfoConverter;
import com.sunstar.club.subject.domain.entity.SubjectInfoBo;
import com.sunstar.club.subject.domain.entity.SubjectOptionBo;
import com.sunstar.club.subject.domain.handler.subject.SubjectTypeHandler;
import com.sunstar.club.subject.domain.handler.subject.SubjectTypeHandlerFactory;
import com.sunstar.club.subject.domain.service.SubjectInfoDomainService;
import com.sunstar.club.subject.infra.basic.entity.SubjectInfo;
import com.sunstar.club.subject.infra.basic.entity.SubjectLabel;
import com.sunstar.club.subject.infra.basic.entity.SubjectMapping;
import com.sunstar.club.subject.infra.basic.service.SubjectInfoService;
import com.sunstar.club.subject.infra.basic.service.SubjectLabelService;
import com.sunstar.club.subject.infra.basic.service.SubjectMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: Shylo Sun
 * @Project: track-club
 * @Date: 2024/2/23 23:43
 */
@Service
@Slf4j
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {

    @Resource
    private SubjectInfoService subjectInfoService;

    @Resource
    private SubjectTypeHandlerFactory subjectTypeHandlerFactory;

    @Resource
    private SubjectMappingService subjectMappingService;

    @Resource
    private SubjectLabelService subjectLabelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SubjectInfoBo subjectInfoBo) {
        if (log.isInfoEnabled()) {
            log.info("SubjectInfoDomainServiceImpl.add.bo:{}", JSON.toJSONString(subjectInfoBo));
        }
        // 假设我们都写在主流程里面
        // 判断type，单选的调用单选的service，多选的调用多选的service
        // 就会存在一大堆的if
        // 所以使用 工厂+策略 模式
        // 一个工厂包含4种类型的策略，根据传入的type自动映射选择处理
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBo);
        subjectInfo.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        subjectInfoService.insert(subjectInfo);

        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        subjectInfoBo.setId(subjectInfo.getId());
        handler.add(subjectInfoBo);

        // 保存分类和标签的映射关系
        List<Integer> categoryIds = subjectInfoBo.getCategoryIds();
        List<Integer> labelIds = subjectInfoBo.getLabelIds();
        List<SubjectMapping> mappingList = new LinkedList<>();
        for (Integer categoryId : categoryIds) {
            for (Integer labelId : labelIds) {
                SubjectMapping mapping = new SubjectMapping();
                mapping.setSubjectId(subjectInfo.getId());
                mapping.setCategoryId(Long.valueOf(categoryId));
                mapping.setLabelId(Long.valueOf(labelId));
                mapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
                mappingList.add(mapping);
            }
        }
        subjectMappingService.bathInsert(mappingList);
    }

    @Override
    public PageResult<SubjectInfoBo> getSubjectPage(SubjectInfoBo subjectInfoBo) {
        PageResult<SubjectInfoBo> pageResult = new PageResult<>();
        pageResult.setPageNo(subjectInfoBo.getPageNo());
        pageResult.setPageSize(subjectInfoBo.getPageSize());
        int start = (subjectInfoBo.getPageNo() - 1) * subjectInfoBo.getPageSize();
        SubjectInfo subjectInfo = SubjectInfoConverter.INSTANCE.convertBoToInfo(subjectInfoBo);
        int count = subjectInfoService.countByCondition(subjectInfo, subjectInfoBo.getCategoryId(), subjectInfoBo.getLabelId());
        if (count == 0) {
            return pageResult;
        }
        List<SubjectInfo> subjectInfoList = subjectInfoService.queryPage(subjectInfo, subjectInfoBo.getCategoryId(), subjectInfoBo.getLabelId(),
                start, subjectInfoBo.getPageSize());
        List<SubjectInfoBo> subjectInfoBoList = SubjectInfoConverter.INSTANCE.convertListInfoToListBo(subjectInfoList);
        pageResult.setRecords(subjectInfoBoList);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public SubjectInfoBo querySubjectInfo(SubjectInfoBo subjectInfoBo) {
        SubjectInfo subjectInfo = subjectInfoService.queryById(subjectInfoBo.getId());

        SubjectTypeHandler handler = subjectTypeHandlerFactory.getHandler(subjectInfo.getSubjectType());
        SubjectOptionBo subjectOptionBo = handler.query(subjectInfo.getId().intValue());
        SubjectInfoBo bo = SubjectInfoConverter.INSTANCE.convertOptionBoAndInfoToInfoBo(subjectOptionBo, subjectInfo);

        SubjectMapping subjectMapping = new SubjectMapping();
        subjectMapping.setSubjectId(subjectInfo.getId());
        subjectMapping.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
        List<SubjectMapping> subjectMappingList = subjectMappingService.queryLabelId(subjectMapping);
        List<Long> labelIdList = subjectMappingList.stream().map(SubjectMapping::getLabelId).collect(Collectors.toList());
        List<SubjectLabel> labelList = subjectLabelService.bathQueryById(labelIdList);
        List<String> labelNameList = labelList.stream().map(SubjectLabel::getLabelName).collect(Collectors.toList());
        bo.setLabelNames(labelNameList);
        return bo;
    }
}
